<script lang="ts" setup>
// FChat 组件用于显示直播聊天内容
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue'
import { dayjs, ElMessage, ElMessageBox } from 'element-plus'
import storage from '@/utils/storage'
// 导入集中式WebSocket服务和类型
import { wsService, SocketMessage } from '../utils/websocketService'
// 导入子组件
import FChatHeader from './FChatHeader.vue'
import FChatContent from './FChatContent.vue'
import FChatFooter from './FChatFooter.vue'
import { addChatApi, bindFdApi } from '@/addon/htscrm/api'
import { useRoute } from 'vue-router'
import FDetailDrawer from '@/addon/htscrm/components/f-detail-drawer'

const inputContent = ref('')
const showEmoji = ref(false)
const showFileDialog = ref(false)
const muteVisible = ref(false)
const muteDuration = ref(10)
const isQuestion = ref(false)
const connectionStatus = ref('disconnected')
const wsConnected = ref(false)

// 消息列表
const messages = reactive<SocketMessage['data'][]>([])
const currentGroup = ref(1)
const messageGroupOptions = reactive([
    {
        label: '全部',
        value: 1
    },
    {
        label: '我的学员',
        value: 2
    },
    {
        label: '讲师消息',
        value: 3
    }
])

const route = useRoute()
const currentUid = computed(() => storage.get('userinfo')?.uid || 1)
const detailDrawerRef = ref()
// 连接状态监听器
const handleConnectionOpen = () => {
    console.log('WebSocket连接已建立')
    connectionStatus.value = 'connected'
    wsConnected.value = true
    ElMessage.success('聊天连接已建立')
}

const handleConnectionClose = () => {
    console.log('WebSocket连接已关闭')
    connectionStatus.value = 'disconnected'
    wsConnected.value = false
}

const handleConnectionError = (error: Error) => {
    console.error('WebSocket连接错误:', error)
    connectionStatus.value = 'error'
    wsConnected.value = false
    ElMessage.error('聊天连接出错，请稍后重试')
}

const handleSendFailed = (data: any) => {
    console.error('消息发送失败:', data)
    ElMessage.error('消息发送失败，请稍后重试')
}

// 消息处理器
const handleChatMessage = (e: SocketMessage) => {
    console.log('收到WebSocket消息:', e)

    // 确保数据格式正确
    if (e && e.message_type === 'group_chat') {
        console.log('收到群聊消息:', e.data)

        messages.push(e.data)
    }
}

// connect 事件
const handleConnect = (e: SocketMessage) => {
    console.log('WebSocket已链接:', e)

    bindFdApi({
        huodong_id: Number(route.params.id),
        fd: e.data.myfd || '',
        uid: currentUid.value
    })
}

onMounted(() => {
    // 检查浏览器兼容性
    if (!wsService.isWebSocketSupported()) {
        ElMessage.error('您的浏览器不支持WebSocket，请使用现代浏览器')
        return
    }
    // 注册事件监听器
    wsService.on('open', handleConnectionOpen)
    wsService.on('close', handleConnectionClose)
    wsService.on('error', handleConnectionError)
    wsService.on('sendFailed', handleSendFailed)
    // 连接WebSocket服务
    wsService.connect()
    // 订阅聊天消息（现在只需要订阅group_chat类型）
    wsService.subscribe('group_chat', handleChatMessage)
    wsService.subscribe('connect', handleConnect)
})

onBeforeUnmount(() => {
    // 取消消息订阅
    wsService.unsubscribe('group_chat', handleChatMessage)
    wsService.unsubscribe('connect', handleConnect)
    // 移除事件监听器
    wsService.off('open', handleConnectionOpen)
    wsService.off('close', handleConnectionClose)
    wsService.off('error', handleConnectionError)
    wsService.off('sendFailed', handleSendFailed)
})

// 发送消息
const sendMessage = async () => {
    if (!inputContent.value) {
        ElMessage.error('请输入消息内容')
        return
    }

    // 创建符合SocketMessage格式的消息
    const socketMsg: SocketMessage = {
        message_type: 'group_chat', // 默认使用group_chat类型
        data: {
            huodong_id: Number(route.params.id), // 假设活动ID为1
            uid: currentUid.value, // 假设当前用户ID为1
            id: Date.now(),
            time: dayjs().format('HH:mm'),
            type: 'text',
            username: '管理员',
            face: 'https://static-pre.fastht.cn/image/2025/11/24/1763991208611-3omlvbku.png',
            content: JSON.stringify({ text: inputContent.value })
        }
    }

    // 2. 构造后端所需数据
    const postdata = {
        message_type: 'group_chat',
        user_type: 'manger',
        ...socketMsg.data
    }

    // 3. 请求后端
    const res: any = await addChatApi(postdata)
    console.log(res)

    socketMsg.data.id = res.data.id

    // 本地显示的消息格式
    const localMessage: SocketMessage['data'] = socketMsg.data

    // 检查连接状态
    if (!wsConnected.value) {
        // 如果未连接，先尝试重连
        wsService.reconnect()
        // 即使连接未建立，也先在本地显示消息
        messages.push(localMessage)
        inputContent.value = ''
        ElMessage.warning('消息已在本地显示，正在尝试连接服务器...')
        return
    }

    // 通过WebSocket服务发送消息
    const success = wsService.send(socketMsg)
    console.log(success)

    if (success) {
        console.log(1111, localMessage)

        // 本地立即显示消息
        messages.push(localMessage)
        inputContent.value = ''
    }
}

// 操作处理
const handleAction = (action: string, message: SocketMessage['data']) => {
    console.log(action, message)

    switch (action) {
        case 'detail':
            detailDrawerRef.value?.show('客户详情', { id: message.uid })
            break
        case 'reply':
            inputContent.value = `@${message.sender || ''} `
            break
        case 'mute':
            muteVisible.value = true
            break
        case 'block':
            ElMessageBox.confirm('确认拉黑该用户?', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消'
            }).then(() => {
                // 执行拉黑逻辑
            })
            break
        case 'withdraw': {
            const index = messages.indexOf(message)
            if (index > -1) {
                messages.splice(index, 1)
            }
            break
        }
    }
}

// 文件处理
const handleFileUpload = (file: File) => {
    console.log(file)
}

// 表情选择处理
const selectEmoji = (emoji: string) => {
    inputContent.value += emoji
}

// 文件上传处理
const handleFileChange = (e: Event) => {
    const input = e.target as HTMLInputElement
    if (input.files?.length) {
        const file = input.files[0]
        handleFileUpload(file)
    }
}
</script>

<template>
  <div class="chat-container">
    <!-- 头部组件 - 消息筛选和连接状态 -->
    <FChatHeader
      v-model:value="currentGroup"
      :options="messageGroupOptions"
    />

    <!-- 内容组件 - 消息列表 -->
    <FChatContent
      :messages="messages"
      :group="currentGroup"
      @user-action="handleAction"
    />

    <!-- 底部组件 - 消息发送区域 -->
    <FChatFooter
      v-model:inputContent="inputContent"
      v-model:showEmoji="showEmoji"
      v-model:showFileDialog="showFileDialog"
      v-model:isQuestion="isQuestion"
      v-model:muteVisible="muteVisible"
      v-model:muteDuration="muteDuration"
      :connectionStatus="connectionStatus"
      @send="sendMessage"
      @selectEmoji="selectEmoji"
      @fileChange="handleFileChange"
    />

    <f-detail-drawer
      ref="detailDrawerRef"
      is="UserDetail"></f-detail-drawer>
  </div>
</template>

<style scoped lang="scss">
.chat-container {
  background-color: #fff;
  height: 100vh;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
}
</style>
